<template>
    <card title="投放策略" class="put-strategy-box">
        <!-- //去掉楼盘去重 -->
        <div v-if="false" class="no-repeat">
            <Switch v-model="isRepeat" size="16px" active-color="#E60044" inactive-color="#dcdee0">
            </Switch>
            <span class="r-text">楼盘去重</span>
            <Popover v-model:show="showPopover" theme="dark" placement="top-end">
                <div class="pop-content">
                    开启时，同一楼盘将优先选择智能屏覆盖，且该楼盘下LCD不再投放；关闭时，楼盘下智能屏、LCD全部投放
                </div>
                <template #reference>
                    <img src="@/assets/img/cph-tips.png" alt="">
                </template>
            </Popover>
        </div>

        <div class="media-box">
            <div class="title">
                请选择您要投放的媒体形式
            </div>
            <div class="tag-box">
                <tags-list
                    :is-multiple="true" :data="mediaTypeList" :selection-data="mediaTypes" :is-disabled="isJc"
                    @click="mediaHandleClick"
                />
            </div>
            <!-- <div class="media-tip">
                <i class="iconfont icon-tishi1"></i>
            </div> -->
        </div>
        <div v-if="strategyList.length" class="strategy-box">
            <div class="title mb-8">
                请设置您的投放策略
            </div>

            <Tabs
                v-model:active="activeTab" title-active-color="#333333" title-inactive-color="#848484" :line-width="20"
                :line-height="4" class="tabs" @change="onTabChange"
            >
                <tab :name="1" title="社区场景">
                    <div v-if="isFromForgetting" class="put-process-forgetting">
                        <div class="put-week">
                            <h5>请设置你的投放周期</h5>
                            <selectRow :show-value="curShowDate" title="开始时间" @on-click="isShowDateSlector = true">
                            </selectRow>
                            <div class="put-process">
                                <putProcess
                                    v-if="curShowDate !== '请选择'" :start-time="curShowDate"
                                    @on-procss-array="onProcessArray"
                                ></putProcess>
                            </div>
                        </div>

                        <div class="put-strategy">
                            <h5>请设置你的投放方式投</h5>
                            <my-cell
                                v-if="mediaTypes?.some((item) => item.value === 1)" label-width="200px"
                                :is-show-arrow="true" :show-bottom-line="mediaTypes.length > 1" label="智能屏: 时长频次"
                                placeholder="请选择" :value="showPinValue" @click="onclickDuaAndFrency(1)"
                            ></my-cell>
                            <my-cell
                                v-if="mediaTypes?.some((item) => item.value === 2)" label-width="200px"
                                :is-show-arrow="true" :show-bottom-line="false" label="LCD: 时长频次" placeholder="请选择"
                                :value="showLcdValue" @click="onclickDuaAndFrency(2)"
                            ></my-cell>
                        </div>
                    </div>

                    <div v-else class="item">
                        <div v-for="(item) in strategyList" :key="item.type">
                            <template v-for="(media, index) in item.list" :key="media.title">
                                <strategy-item
                                    :title="getMediaTitle(media.title, index)" :show-delete="index > 0"
                                    :strategy-item="media" @delete-strategy="deleteStrategy(item.list, index)"
                                    @change-form-date="val => changeFormDate(val, index, item.list)"
                                ></strategy-item>
                            </template>
                            <div class="add-strategy" @click="addStrategy(item)">
                                +新增策略
                            </div>
                        </div>
                    </div>
                </tab>
                <tab :name="2" title="商务场景">
                    <div class="expect">
                        <img src="@/assets/img/expect.png" alt="敬请期待">
                    </div>
                </tab>
            </Tabs>
        </div>
    </card>
    <my-calendar
        :default-date="startDate" :is-show="isShowDateSlector" @confirm="onDateSelect"
        @close="isShowDateSlector = false"
    />
    <FrequencySelecter
        :duration-frequency="[pinDuration, pinFrequency]" :formator-columns="formatorColums"
        :is-show="showFrequencyPickerPin" @close="showFrequencyPickerPin = false" @confirm="frequencyConfirmPin"
    >
    </FrequencySelecter>
    <FrequencySelecter
        :duration-frequency="[lcdDuration, lcdFrequency]" :formator-columns="formatorColums"
        :is-show="showFrequencyPickerLcd" @close="showFrequencyPickerLcd = false" @confirm="frequencyConfirmLcd"
    >
    </FrequencySelecter>
    <!-- <Picker title="投放方式" :is-show="putTypeShow" :columns="putTypeColumns" @close="putTypeShow = false" @confirm="putTypeConfirm"></Picker> -->
</template>

<script lang="ts" setup name="PutStrategy">
import Card from '@/components/Card/index.vue';
import tagsList from '@/components/tagsList.vue';
import StrategyItem from './StrategyItem.vue';
import { convertToChineseNumeral, getNextSatDate } from '@/utils/index';
import { ref, reactive, PropType, watch, Ref, toRefs } from 'vue';
// import { store } from '@/store';
import { StrategyItemData, MediaItem, StrategyListData } from '../strategy.module';
import dayjs from 'dayjs';
import { mediaTypeList1 } from '@/utils/consts';
import { Switch, Popover, Tabs, Tab } from 'vant';
import putProcess from '../../preventForgetting/components/putProcess.vue';
import selectRow from '../../preventForgetting/components/selectRow.vue';
import { IProcessInfo } from '../../preventForgetting/preventForgeting';
import MyCalendar from '@/components/MyCalendar/index.vue';
import { nextTick } from 'vue';
import { onMounted } from 'vue';
import FrequencySelecter from '@/components/FrequencySelecter/index.vue';
import MyCell from '@/components/MyCell/index.vue';
import { strategySpecsItem } from '@/api/brandBreakout';
// import Picker from '@/components/DurationSelecter/index.vue';

const emit = defineEmits(['onTabChange', 'changeData']);
const activeTab = ref(1); // 1 :社区 2：商务网
function onTabChange(val: number) {
    activeTab.value = val;
    emit('onTabChange', activeTab.value);
}

const showPopover = ref(false);
const isRepeat = ref(false);
const props = defineProps({
    // 已经选择的媒体类型
    mediaTypeSelected: {
        type: Array as PropType<(string | number)[]>,
        default: () => [],
    },
    isJc: {
        type: Boolean,
        default: false,
    },
    isFromForgetting: {
        type: Boolean,
        default: false,
    }
});

// interface MediaItem {
//     [key: string]: string | number;
// }
const mediaLabel = 'label';
const mediaValue = 'value';
let mediaTypeList = mediaTypeList1;
if (props.isJc) {
    mediaTypeList = mediaTypeList.filter((item) => {
        return item.label === '智能屏';
    });
} else {
    mediaTypeList = mediaTypeList.filter((item) => {
        return item.label !== '海报';
    });
}
// 最优策略
// const optimalMediaType: number = store.state.app.home.optimalMediaType;
const optimalMediaType = 1;

let defaultMediaTypeIds: (number | string)[] = [];
let defaultMediaTypes: MediaItem[] = [{ value: 1, label: '智能屏' },];
if (props.mediaTypeSelected.length) {
    const { mediaTypeSelected } = toRefs(props);
    defaultMediaTypeIds = mediaTypeSelected.value;
    defaultMediaTypes = mediaTypeList.filter(item => defaultMediaTypeIds.includes(item.value));
} else if (optimalMediaType) { // 媒体类型默认选择首页CPH最低的媒体形式
    defaultMediaTypes = mediaTypeList.filter(item => item.value.toString() === optimalMediaType.toString());
}
const mediaTypes = ref<Array<MediaItem>>(defaultMediaTypes);

// interface StrategyListData {
//     type: number | string; // 媒体类型
//     name: number | string;
//     list: StrategyItemData[];
// }

const strategyList = ref<Array<StrategyListData>>([]);

// watch(
//     () => mediaTypes.value,
//     () => {
//         emit('changeData', mediaTypes.value, strategyList.value);
//     },
//     {
//         deep: true,
//     },
// );

// 对于京潮计划、标签选点、lbs投放三种软产品,在投放页面可以自由选择媒体类型. 接口接收媒体类型有顺序要求,最优策略需要放在媒体类型列表参数(mediaTypes)的第一个位置.最优策略是首页计算cph最低的智能屏或者lcd.
// 若选择的媒体类型不包含最优策略, 则媒体海报需要在lcd/智能屏之后
function mediaTypeHandle(): MediaItem[] {
    // 是否包含最有策略
    // const optimalMediaTypeIsincludes = mediaTypes.value.find(item => item.value === optimalMediaType);
    // let medaiaTypeSort: MediaItem[] = mediaTypes.value.filter(item => item.value !== optimalMediaType);
    // if(optimalMediaTypeIsincludes) {
    //     const optimalMediaTypeObj = mediaTypeList.find(item => item.value === optimalMediaType);
    //     if(optimalMediaTypeObj) {
    //         medaiaTypeSort.unshift(optimalMediaTypeObj as MediaItem);
    //     }
    // }
    const medaiaTypeSort = mediaTypes.value.sort((a, b) => {
        return +a.value - +b.value;
    });
    return medaiaTypeSort;
}

// 策略名
function getMediaTitle(name: string | number, index: number) {
    return name.toString() + convertToChineseNumeral(index + 1);
}

function addStrategy(item: StrategyListData) {
    let duration: number | string = '';
    let frequency: number | string = '';
    let framePublishMethod: number | string = '';
    let framePublishMethodLabel = '';
    if (item.type === 1) {
        duration = 15;
        frequency = 300;
    } else if (item.type === 2) {
        duration = 15;
        frequency = 150;
    } else if (item.type === 3) {
        framePublishMethod = 1;
        framePublishMethodLabel = '一梯一框';
    }
    // 默认未来四周
    const startDate = dayjs(getNextSatDate()).format('YYYY-MM-DD');
    const endDate = dayjs(startDate).add(3 * 7 + 6, 'day').format('YYYY-MM-DD');
    console.log(startDate, endDate);
    const durationFrequency = duration.toString() + 's' + frequency.toString() + '次';
    const strategyItem = ref<StrategyItemData>({
        mediaType: item.type,
        title: item.name.toString() + '-' + '策略',
        duration: duration,
        frequency: frequency,
        durationFrequency: durationFrequency,
        framePublishMethod: framePublishMethod,
        framePublishMethodLabel: framePublishMethodLabel,
        startDate: startDate,
        endDate: endDate,
        dateRangeListLabel: startDate + '至' + endDate,
    });
    item.list.push(strategyItem.value);
    // emit('changeData');
}


// 投放策略数据增加和删除处理（根据媒体形式）
function initStrategyList() {
    const selectedMediaKey: (string | number)[] = mediaTypes.value.map(item => item[mediaValue]);
    strategyList.value = strategyList.value.filter((item: StrategyListData) => selectedMediaKey.includes(item.type));
    const strategyListKeys: (string | number)[] = strategyList.value.map(item => item.type);
    if (selectedMediaKey.length > strategyListKeys.length) {
        mediaTypes.value.forEach(item => {
            if (!strategyListKeys.includes(item[mediaValue])) {
                const mediaItem = {
                    type: item[mediaValue],
                    name: item[mediaLabel],
                    list: reactive([]),
                };
                strategyList.value.push(mediaItem);
                addStrategy(mediaItem);
            }
        });
    } else {
        // emit('changeData');
    }
}



function deleteStrategy(list: StrategyItemData[], index: number) {
    list.splice(index, 1);
}

function changeFormDate(form: StrategyItemData, index: number, list: StrategyItemData[]) {
    list[index] = form;
}

watch(
    () => strategyList.value,
    (val) => {
        let strategySpecs: StrategyItemData[] = [];
        val.forEach(item => {
            strategySpecs = strategySpecs.concat(item.list);
        });
        if (!props.isFromForgetting) {
            emit('changeData', mediaTypeHandle(), strategySpecs);
        }
    },
    {
        deep: true,
    },
);
initStrategyList();



// ---标签选点防遗忘包相关逻辑
const curShowDate = ref('请选择');


const startDate = ref('');
// 设置默认开始日期
const week = dayjs().day();
if (week === 6) {
    startDate.value = dayjs().day(6).add(1, 'week').format('YYYY-MM-DD');
} else {
    startDate.value = dayjs().day(6).format('YYYY-MM-DD');
}

onMounted(async () => {
    await nextTick(() => {
        curShowDate.value = startDate.value;
    });
});



const isShowDateSlector = ref(false);
function onDateSelect(data: Date) {
    // date.value = formatDate(value);
    startDate.value = dayjs(data).format('YYYY-MM-DD');
    curShowDate.value = startDate.value;
    isShowDateSlector.value = false;// 选中日期传给后台需要加上四周固定日期
    // await getStatistics();
}

const showPinValue = ref('15秒300次');
const showFrequencyPickerPin = ref(false);
const pinDuration = ref(15);
const pinFrequency = ref(300);

const showLcdValue = ref('15秒300次');
const showFrequencyPickerLcd = ref(false);
const lcdDuration = ref(15);
const lcdFrequency = ref(300);


// function resetPin(){
//     showPinValue.value = '15秒300次';
//     pinDuration.value = 15;
//     pinFrequency.value = 300;
// }

// function resetLcd(){
//     showLcdValue.value = '15秒300次';
//     lcdDuration.value= 15;
//     lcdFrequency.value = 300;
// }

let curProcessArray: IProcessInfo[] = []; // 当前选择的进度信息数组
function handleParams() {
    const processInfo = curProcessArray;
    const strategySpecs: strategySpecsItem[] = [];

    const singleMediaTypes = mediaTypes.value.map((item) => {
        return item.value;
    });
    singleMediaTypes.forEach((type: number | string) => {
        if (type === 1 || type === 2) {
            if (processInfo) {
                processInfo.forEach((processItem: IProcessInfo) => {
                    const { startTimeReal, endTime } = processItem;
                    const duration = type === 1 ? pinDuration.value : lcdDuration.value;
                    const frequency = type === 1 ? pinFrequency.value : lcdFrequency.value;
                    const strategyItem: strategySpecsItem = {
                        mediaType: type,
                        duration,
                        frequency,
                        startDate: startTimeReal,
                        endDate: endTime
                    };
                    strategySpecs.push(strategyItem);
                });
            }
        } else {
            // 暂时没有框的场景
            // processInfo?.forEach((processItem: IProcessInfo) => {
            //     const { startTimeReal, endTime } = processItem;
            //     const strategyItem: strategySpecsItem = {
            //         mediaType: type,
            //         framePublishMethod: isUseDefault ? 1 : frameInfo.framePublishMethod,
            //         startDate: startTimeReal,
            //         endDate: endTime
            //     };
            //     strategySpecs.push(strategyItem);
            // });
        }
    });
    if (props.isFromForgetting) {
        emit('changeData', mediaTypeHandle(), strategySpecs);
    }
}

function mediaHandleClick(data: []) {
    mediaTypes.value = data;
    if (!props.isFromForgetting) {
        initStrategyList();
    } else {
        // if(mediaTypes.value.some((item)=>item.value === 1)){
        //     resetPin();
        // }
        // if(mediaTypes.value.some((item)=>item.value === 2)){
        //     resetLcd();
        // }
        handleParams();
    }
}


function frequencyConfirmPin(value: string[]) {
    console.log('value', value);
    showFrequencyPickerPin.value = false;
    const duration = value[0].slice(0, value[0].length - 1);

    pinDuration.value = +duration;
    const frequency = value[1].slice(0, value[1].length - 1);
    pinFrequency.value = +frequency;
    const durationFrequency = value.join('');
    showPinValue.value = durationFrequency;
    handleParams();
}


function frequencyConfirmLcd(value: string[]) {
    showFrequencyPickerLcd.value = false;
    const duration = value[0].slice(0, value[0].length - 1);
    const frequency = value[1].slice(0, value[1].length - 1);
    lcdDuration.value = +duration;
    lcdFrequency.value = +frequency;
    const durationFrequency = value.join('');
    showLcdValue.value = durationFrequency;
    handleParams();
}
function formatorColums(cols: Ref<{
    values: string[],
    defaultIndex: number;
}[]>) {
    console.log('cols', cols);
    const timesCols = cols.value[0];
    timesCols.values = cols.value[0].values.filter((val) => {
        return val === '5s' || val === '10s' || val === '15s';
    });
    cols.value[1].values = cols.value[1].values.filter((val) => {
        return val === '300次';
    });
}
function onclickDuaAndFrency(item: number) {
    if (item === 1) {
        showFrequencyPickerPin.value = true;
    } else if (item === 2) {
        showFrequencyPickerLcd.value = true;
    }
}



// 当选择的投放阶段信息变化时，刷新本页投放信息
function onProcessArray(val: IProcessInfo[]) {
    curProcessArray = val;
    // 拆分策略阶段
    // 拆阶段
    handleParams();
}

</script>

<style scoped lang="scss">
.put-strategy-box {
    position: relative;
    margin-top: 12px;
    padding-bottom: 0;

    .media-box {
        margin-top: 16px;

        .title {
            font-weight: 600;
            font-size: 14px;
            color: #333333;
        }

        .tag-box {
            padding-top: 12px;
            // padding-bottom: 8px;
        }

        .media-tip {
            font-weight: 400;
            font-size: 12px;
            color: #b5b5b5;

            .tip-label {
                margin-left: 8px;
            }
        }
    }

    .strategy-box {
        padding-top: 10px;

        .title {
            font-weight: 600;
        }

        .add-strategy {
            font-size: 14px;
            color: #397ff8;
            text-align: center;
            padding: 12px 0;
        }

        .put-process-forgetting {
            .put-week {
                margin-bottom: 10px;

                h5 {
                    font-size: 14px;
                    font-weight: 600;
                    margin-top: 24px;
                }

                .put-process {
                    margin-top: 16px;
                    margin-bottom: 24px;
                }
            }

            .put-strategy {
                h5 {
                    font-size: 14px;
                    font-weight: 600;
                }
            }
        }
    }

    .no-repeat {
        position: absolute;
        width: 120px;
        top: 15px;
        right: 10px;
        display: flex;
        margin-top: 3px;
        justify-content: flex-end;
        align-items: center;

        .r-text {
            padding: 0 5px;
            font-size: 12px;
            color: #333333;
            margin-right: 6px;
        }

        img {
            width: 14px;
            height: 14px;
            vertical-align: middle;
            margin-left: -5px;
        }
    }
}

// :deep(.van-tabs) {
//     [class~="van-tabs__wrap"] {
//         margin-top: 16px;
//         padding-bottom: 10px;
//         border-bottom: 1px solid #eee;
//     }
//     [class~="van-tab--active"] {
//         font-weight: 600;
//     }
// }
.expect {
    width: 100%;
    height: 240px;
    position: relative;

    img {
        position: absolute;
        left: 50%;
        top: 40%;
        transform: translate(-50%, -50%);
        width: 189px;
        height: auto;
    }

    :deep(.cell) {
        border: 0;
        background-color: pink;
    }
}

.pop-content {
    padding: 10px;
    font-size: 12px;
    line-height: 19px;
    width: 280px;
}
</style>
